<?php

// 检测站点的运行级别
function check_runlevel() {
	global $conf, $method, $gid;
	if($gid == 1) return;
	switch ($conf['runlevel']) {
		case 0: message(-1, $conf['runlevel_reason']); break;
		case 1: message(-1, lang('runlevel_reason_1')); break;
		case 2: ($gid == 0 || $method != 'GET') AND message(-1, lang('runlevel_reason_2')); break;
		case 3: $gid == 0 AND message(-1, lang('runlevel_reason_3')); break;
		case 4: $method != 'GET' AND message(-1, lang('runlevel_reason_4')); break;
	}
}

/*
	message(0, '登录成功');
	message(1, '密码错误');
	message(-1, '数据库连接失败');
	
	code:
		< 0 全局错误，比如：系统错误：数据库丢失连接/文件不可读写
		= 0 正确
		> 0 一般业务逻辑错误，可以定位到具体控件，比如：用户名为空/密码为空
*/
function message($code, $message, $extra = array()) {
	global $ajax,$conf;
	
	$arr = $extra;
	$arr['code'] = $code.'';
	$arr['message'] = $message;
	
	// hook model_message_start.php
	
	// 防止 message 本身出现错误死循环
	static $called = FALSE;
	$called ? exit(xn_json_encode($arr)) : $called = TRUE;
	
	if($ajax) {
		echo xn_json_encode($arr);
	} else {
		$header = array(
			'title'=>$conf['sitename'],
			'keywords' => $conf['keywords'],
			'description' => $conf['sitebrief'],
		);
		if(defined('MESSAGE_HTM_PATH')) {
			include _include(MESSAGE_HTM_PATH);
		} else {
			include _include(APP_PATH."view/htm/message.htm");
		}
	}
	// hook model_message_end.php
	exit;
}

// 上锁
function xn_lock_start($lockname = '', $life = 10) {
	global $conf, $time;
	$lockfile = $conf['tmp_path'].'lock_'.$lockname.'.lock';
	if(is_file($lockfile)) {
		// 大于 $life 秒，删除锁
		if($time - filemtime($lockfile) > $life) {
			xn_unlink($lockfile);
		} else {
			// 锁存在，上锁失败。
			return FALSE;
		}
	}
	
	$r = file_put_contents($lockfile, $time, LOCK_EX);
	return $r;
}

// 删除锁
function xn_lock_end($lockname = '') {
	global $conf, $time;
	$lockfile = $conf['tmp_path'].'lock_'.$lockname.'.lock';
	xn_unlink($lockfile);
}

// 导出excel
function export_excel($title='导出数据',$colname=array(),$data=array(),$filename='导出数据'){
	set_time_limit(0);//不限制超时时间
 	ini_set('memory_limit', '-1');//不限制内存
	require_once XIUNOPHP_PATH.'PHPExcel/PHPExcel.php';
	$excel = new PHPExcel();
	$activeSheet = $excel->getActiveSheet();
	$cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
	//标题
	$row = 1;//初始第一行
	$col_nums = count($colname);//总列数
	$activeSheet->mergeCells('A'.$row.':'.$cellName[$col_nums-1].$row);//合并单元格
	$activeSheet->setCellValue('A'.$row, $title);//设置合并后的单元格内容
	$activeSheet->getStyle('A'.$row)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//居中
	$activeSheet->getStyle('A'.$row)->getFont()->setBold(true);//加粗
	$activeSheet->getStyle('A'.$row)->getFont()->setSize(16);//字体大小
	$activeSheet->getStyle('A'.$row)->getFont()->getColor()->setARGB('001941A5');//字体颜色
	//列名
	if($colname){
		$row++;//下一行(第二行)
		$col = 0;//初始第一列
		foreach($colname AS $v){   
			$activeSheet->setCellValue($cellName[$col].$row, $v);//设置单元格内容
			$activeSheet->getStyle($cellName[$col].$row)->getFont()->setBold(true);//加粗
			$activeSheet->getDefaultColumnDimension($cellName[$col])->setWidth(20);//列宽度
			$activeSheet->getStyle($cellName[$col].$row)->getFont()->getColor()->setARGB('00CCCCCC');//字体颜色
			$col++;//下一列
		}
	}
	//数据
	if($data){
		$row++;//下一行(第三行)
		foreach($data AS $_v){
			$col = 0;//初始第一列
			foreach($_v AS $_cell){
				$activeSheet->setCellValue($cellName[$col] . $row, $_cell);//设置单元格内容
				$col++;//下一列
			}
			$row++;//下一行
		}
	}
	//文件名
	$filename=$filename.'('.date('Y-m-d H:i:s').')';
	//输出下载excel
	header("Pragma: public");
	header("Expires: 0");
	header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
	header("Content-Type:application/force-download");
	header("Content-Type:application/vnd.ms-execl");
	header("Content-Type:application/octet-stream");
	header("Content-Type:application/download");;
	header("Content-Disposition:attachment;filename=$filename.xls");//文件名
	header("Content-Transfer-Encoding:binary");
	$excelWrite = PHPExcel_IOFactory::createWriter($excel, 'Excel5');
	$excelWrite->save('php://output');
	exit;
}


/*
 * 上传图片
 * @param	$data	base64格式的图片数据
 * @param	$name	图片名称
 * @param	$path	保存路径
 * @param	$iscut	是否压缩	默认是
 * @param	$max	最大图片大小(MB)	默认8MB
 */
function image_upload($data,$name,$path,$iscut=true,$max=8){
	$data = base64_decode_file_data($data);
	$size = strlen($data);
	$size > $max*1024*1000 AND message(-1, lang('filesize_too_large', array('maxsize'=>$max.'M')));
	$url = $path.$name;
	!is_dir($path) AND (mkdir($path, 0777, TRUE) OR message(-2, lang('directory_create_failed')));
	file_put_contents($url,$data) OR message(-1, lang('write_to_file_failed'));
	if($iscut){
		include APP_PATH.'xiunophp/xn_image_cut.class.php';
		$percent = 1548000 / $size;
		if($percent<1){
			$cut = new ImageCut($url);  
			$cut->percent = $percent;  
			$cut->openImage();  
			$cut->thumpImage();  
			$cut->saveImage($url); 
		} 
	}
}


/*
 * 读取幻灯片的商品信息
 * @return	$res	商品信息集
 */
function ppt(){
	$res = db_find('common_ppt', array(), array('orderby'=>'1'), 1, 1000);
	return $res;
}


?>